package com.liuqi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuqi.common.Constants;
import com.liuqi.controller.dto.UserDTO;
import com.liuqi.entity.Menu;
import com.liuqi.entity.User;
import com.liuqi.exception.ServiceException;
import com.liuqi.mapper.RoleMapper;
import com.liuqi.mapper.RoleMenuMapper;
import com.liuqi.mapper.UserMapper;
import com.liuqi.service.MenuService;
import com.liuqi.service.UserService;
import com.liuqi.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务类实现
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private static final Log LOG = Log.get();

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleMenuMapper roleMenuMapper;//引入关联关系表
    @Resource
    private MenuService menuService;

    public boolean saveUser(User user) {
        /*if (user.getId() == null) {
            return save(user);//mybatis-plus提供的方法，表示插入数据

        } else {
            return updateById(user);
        }*/
        return saveOrUpdate(user);
    }

    @Override
    public UserDTO login(UserDTO userDTO) {
        /*QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
       *//* User one = getOne(queryWrapper);
        return one != null;*//*
        //防止出现脏数据（同一个数据出现两次）
       *//* //方式一
        List<User> list = list(queryWrapper);
        return list.size()!=0;*//*
        User one;
        try {
            one = getOne(queryWrapper);//从数据库查询用户信息
        } catch (Exception e) {//数据库中有脏数据
            //e.printStackTrace();
            LOG.error(e);
            //return false;
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }*/
        User one = getUserInfo(userDTO);
        if (one != null) {//查询到的数据不为空
            BeanUtil.copyProperties(one, userDTO, true);

            //在返回数据之前设置token
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            userDTO.setToken(token);

            String role = one.getRole();//类似于ROLE_ADMIN
            /*Integer roleId = roleMapper.selectByFlag(role);*/
            /*//当前角色的所有权限菜单id集合
            List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);

            //查出系统所有的权限菜单
            List<Menu> menus = menuService.findMenus("");

            //new一个最后筛选完成之后的list
            ArrayList<Menu> roleMenus = new ArrayList<>();
            //筛选当前用户角色的菜单
            for (Menu menu : menus) {
                if (menuIds.contains(menu.getId())) {
                    roleMenus.add(menu);
                }
                List<Menu> children = menu.getChildren();
                //removeIf():移除children里面不在menuIds集合中的元素
                children.removeIf(child -> !menuIds.contains(child.getId()));
            }*/

            //设置用户的菜单列表
            List<Menu> roleMenus = getRoleMenus(role);
            userDTO.setMenus(roleMenus);
            return userDTO;
        } else {//用户为null
            throw new ServiceException(Constants.CODE_600, "用户名或者密码错误");
        }
    }

    @Override
    public User register(UserDTO userDTO) {
        User one = getUserInfo(userDTO);//根据注册传过来的信息查询数据库得到one
        if (one == null) {//数据库中没有one
            one = new User();
            BeanUtil.copyProperties(userDTO, one, true);//将userDTOcopy给one
            save(one);//把copy完之后的用户对象储存到数据库
        } else {
            throw new ServiceException(Constants.CODE_500, "用户已存在");
        }
        return one;
    }

    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
        User one;
        try {
            one = getOne(queryWrapper);//从数据库查询用户信息
        } catch (Exception e) {//数据库中有脏数据
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }
    /*@Resource
    private UserMapper userMapper;*/

    /*public int save(User user) {
        if (user.getId() == null) {//user没有id，则表示是新增
            return userMapper.insert(user);
        } else {//否则为更新
            return userMapper.update(user);
        }
    }*/

    /*public List<User> findAll() {
        return userMapper.findAll();
    }*/

    /**
     * 获取当前角色的权限菜单列表
     * @param roleFlag
     * @return
     */
    private List<Menu> getRoleMenus(String roleFlag){
        Integer roleId = roleMapper.selectByFlag(roleFlag);
        //当前角色的所有权限菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);

        //查出系统所有的权限菜单
        List<Menu> menus = menuService.findMenus("");

        //new一个最后筛选完成之后的list
        ArrayList<Menu> roleMenus = new ArrayList<>();
        //筛选当前用户角色的菜单
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())) {
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            //removeIf():移除children里面不在menuIds集合中的元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        return roleMenus;
    }
}
